<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>mobx常用方法梳理 | 伊水河的博客</title>
    <meta name="generator" content="VuePress 1.7.1">
    <link rel="icon" href="/logo.png">
    <meta name="description" content="SO FAR SO GOOD">
    <meta name="twitter:title" content="mobx常用方法梳理">
    <meta name="twitter:description" content="">
    <meta name="twitter:card" content="summary">
    <meta name="twitter:url" content="https://yihe.cool/guide/relearnMobx.html">
    <meta property="og:type" content="article">
    <meta property="og:title" content="mobx常用方法梳理">
    <meta property="og:description" content="">
    <meta property="og:url" content="https://yihe.cool/guide/relearnMobx.html">
    <meta property="article:author" content="伊水河">
    <meta property="article:published_time" content="2020-11-26T00:00:00.000Z">
    <meta property="article:tag" content="mobx">
    <meta itemprop="name" content="mobx常用方法梳理">
    <meta itemprop="description" content="">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
    
    <link rel="preload" href="/assets/css/0.styles.152c4062.css" as="style"><link rel="preload" href="/assets/js/app.2d22f3f9.js" as="script"><link rel="preload" href="/assets/js/3.6721f6a0.js" as="script"><link rel="preload" href="/assets/js/1.546ea5a7.js" as="script"><link rel="preload" href="/assets/js/19.73f82cea.js" as="script"><link rel="prefetch" href="/assets/js/10.b827ae65.js"><link rel="prefetch" href="/assets/js/11.5e38b612.js"><link rel="prefetch" href="/assets/js/12.3f3699b0.js"><link rel="prefetch" href="/assets/js/13.7d83bc51.js"><link rel="prefetch" href="/assets/js/14.2ea90c77.js"><link rel="prefetch" href="/assets/js/15.7df6d74c.js"><link rel="prefetch" href="/assets/js/16.33c1bac8.js"><link rel="prefetch" href="/assets/js/17.1aef86d1.js"><link rel="prefetch" href="/assets/js/18.b74cd2bd.js"><link rel="prefetch" href="/assets/js/20.6354096e.js"><link rel="prefetch" href="/assets/js/21.fd87273b.js"><link rel="prefetch" href="/assets/js/22.f90ee83e.js"><link rel="prefetch" href="/assets/js/23.e5f4f0a1.js"><link rel="prefetch" href="/assets/js/24.239130eb.js"><link rel="prefetch" href="/assets/js/25.db493ad9.js"><link rel="prefetch" href="/assets/js/26.26f3df98.js"><link rel="prefetch" href="/assets/js/27.d55bc04b.js"><link rel="prefetch" href="/assets/js/28.ac3a437a.js"><link rel="prefetch" href="/assets/js/29.9abce28f.js"><link rel="prefetch" href="/assets/js/30.ea843119.js"><link rel="prefetch" href="/assets/js/31.30a083bf.js"><link rel="prefetch" href="/assets/js/32.5f0b6b12.js"><link rel="prefetch" href="/assets/js/33.11456c83.js"><link rel="prefetch" href="/assets/js/34.e9ede601.js"><link rel="prefetch" href="/assets/js/35.17e5bb78.js"><link rel="prefetch" href="/assets/js/36.2f441457.js"><link rel="prefetch" href="/assets/js/37.e9fa7538.js"><link rel="prefetch" href="/assets/js/38.6bd1c237.js"><link rel="prefetch" href="/assets/js/39.8b0b956e.js"><link rel="prefetch" href="/assets/js/4.3ad057db.js"><link rel="prefetch" href="/assets/js/40.89ef1936.js"><link rel="prefetch" href="/assets/js/41.48d0560d.js"><link rel="prefetch" href="/assets/js/42.f804c44f.js"><link rel="prefetch" href="/assets/js/43.9dc6d003.js"><link rel="prefetch" href="/assets/js/44.3033d12c.js"><link rel="prefetch" href="/assets/js/45.60834ce1.js"><link rel="prefetch" href="/assets/js/46.c7eaf70d.js"><link rel="prefetch" href="/assets/js/47.a618490c.js"><link rel="prefetch" href="/assets/js/48.39a68335.js"><link rel="prefetch" href="/assets/js/49.1fa3bd55.js"><link rel="prefetch" href="/assets/js/5.4b2144a0.js"><link rel="prefetch" href="/assets/js/50.0ad5db28.js"><link rel="prefetch" href="/assets/js/51.843c519b.js"><link rel="prefetch" href="/assets/js/52.47d63846.js"><link rel="prefetch" href="/assets/js/53.5284b79d.js"><link rel="prefetch" href="/assets/js/54.b10b8ac1.js"><link rel="prefetch" href="/assets/js/55.3780915d.js"><link rel="prefetch" href="/assets/js/56.4a811b5c.js"><link rel="prefetch" href="/assets/js/57.228652ee.js"><link rel="prefetch" href="/assets/js/58.ef55d2ec.js"><link rel="prefetch" href="/assets/js/59.cbb81185.js"><link rel="prefetch" href="/assets/js/6.3dafc094.js"><link rel="prefetch" href="/assets/js/60.5257b363.js"><link rel="prefetch" href="/assets/js/61.03db625c.js"><link rel="prefetch" href="/assets/js/62.5982e690.js"><link rel="prefetch" href="/assets/js/63.0eccb44b.js"><link rel="prefetch" href="/assets/js/64.d92985de.js"><link rel="prefetch" href="/assets/js/65.4fd6aed1.js"><link rel="prefetch" href="/assets/js/66.acaf73d6.js"><link rel="prefetch" href="/assets/js/67.6db75c01.js"><link rel="prefetch" href="/assets/js/68.1dce863f.js"><link rel="prefetch" href="/assets/js/69.4222a30b.js"><link rel="prefetch" href="/assets/js/7.be8adaa3.js"><link rel="prefetch" href="/assets/js/8.3121f1c6.js"><link rel="prefetch" href="/assets/js/9.03dc3458.js">
    <link rel="stylesheet" href="/assets/css/0.styles.152c4062.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container no-sidebar" data-v-2d5f533b><div data-v-2d5f533b><div id="loader-wrapper" class="loading-wrapper" data-v-d48f4d20 data-v-2d5f533b data-v-2d5f533b><div class="loader-main" data-v-d48f4d20><div data-v-d48f4d20></div><div data-v-d48f4d20></div><div data-v-d48f4d20></div><div data-v-d48f4d20></div></div> <!----> <!----></div> <div class="password-shadow password-wrapper-out" style="display:none;" data-v-64685f0e data-v-2d5f533b data-v-2d5f533b><h3 class="title" style="display:none;" data-v-64685f0e data-v-64685f0e>伊水河的博客</h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-64685f0e data-v-64685f0e><input type="password" value="" data-v-64685f0e> <span data-v-64685f0e>Konck! Knock!</span> <button data-v-64685f0e>OK</button></label> <div class="footer" style="display:none;" data-v-64685f0e data-v-64685f0e><span data-v-64685f0e><i class="iconfont reco-theme" data-v-64685f0e></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-64685f0e>vuePress-theme-reco</a></span> <span data-v-64685f0e><i class="iconfont reco-copyright" data-v-64685f0e></i> <a data-v-64685f0e><span data-v-64685f0e>伊水河</span>
            
          <span data-v-64685f0e>2020 - </span>
          2021
        </a></span></div></div> <div class="hide" data-v-2d5f533b><header class="navbar" data-v-2d5f533b><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><!----> <span class="site-name">伊水河的博客</span></a> <div class="links"><div class="color-picker"><a class="color-button"><i class="iconfont reco-color"></i></a> <div class="color-picker-menu" style="display:none;"><div class="mode-options"><h4 class="title">Choose mode</h4> <ul class="color-mode-options"><li class="dark">dark</li><li class="auto active">auto</li><li class="light">light</li></ul></div></div></div> <div class="search-box"><i class="iconfont reco-search"></i> <input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/categories/前端/" class="nav-link"><i class="iconfont reco-blog"></i>
  前端
</a></div><div class="nav-item"><a href="/categories/leetcode/" class="nav-link"><i class="iconfont reco-coding"></i>
  力扣
</a></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  标签
</a></div><div class="nav-item"><a href="/note/" class="nav-link"><i class="iconfont reco-suggestion"></i>
  笔记
</a></div><div class="nav-item"><a href="/todo/" class="nav-link"><i class="iconfont reco-document"></i>
  TODO
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-account"></i>
      关于
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="https://juejin.cn/user/571401777456621" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-juejin"></i>
  掘金
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://yishuihe.gitee.io" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-mayun"></i>
  码云
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://github.com/lixiang89" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-github"></i>
  github
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://node.kg.qq.com/personal?uid=659d9d802d253e8231" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont "></i>
  全民K歌
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div> <!----></nav></div></header> <div class="sidebar-mask" data-v-2d5f533b></div> <aside class="sidebar" data-v-2d5f533b><div class="personal-info-wrapper" data-v-ca798c94 data-v-2d5f533b><img src="/b.jpg" alt="author-avatar" class="personal-img" data-v-ca798c94> <h3 class="name" data-v-ca798c94>
    伊水河
  </h3> <div class="num" data-v-ca798c94><div data-v-ca798c94><h3 data-v-ca798c94>51</h3> <h6 data-v-ca798c94>文章</h6></div> <div data-v-ca798c94><h3 data-v-ca798c94>13</h3> <h6 data-v-ca798c94>标签</h6></div></div> <hr data-v-ca798c94></div> <nav class="nav-links"><div class="nav-item"><a href="/categories/前端/" class="nav-link"><i class="iconfont reco-blog"></i>
  前端
</a></div><div class="nav-item"><a href="/categories/leetcode/" class="nav-link"><i class="iconfont reco-coding"></i>
  力扣
</a></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  标签
</a></div><div class="nav-item"><a href="/note/" class="nav-link"><i class="iconfont reco-suggestion"></i>
  笔记
</a></div><div class="nav-item"><a href="/todo/" class="nav-link"><i class="iconfont reco-document"></i>
  TODO
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-account"></i>
      关于
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="https://juejin.cn/user/571401777456621" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-juejin"></i>
  掘金
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://yishuihe.gitee.io" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-mayun"></i>
  码云
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://github.com/lixiang89" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-github"></i>
  github
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://node.kg.qq.com/personal?uid=659d9d802d253e8231" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont "></i>
  全民K歌
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div> <!----></nav> <!----> </aside> <div class="password-shadow password-wrapper-in" style="display:none;" data-v-64685f0e data-v-2d5f533b><h3 class="title" style="display:none;" data-v-64685f0e data-v-64685f0e>mobx常用方法梳理</h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-64685f0e data-v-64685f0e><input type="password" value="" data-v-64685f0e> <span data-v-64685f0e>Konck! Knock!</span> <button data-v-64685f0e>OK</button></label> <div class="footer" style="display:none;" data-v-64685f0e data-v-64685f0e><span data-v-64685f0e><i class="iconfont reco-theme" data-v-64685f0e></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-64685f0e>vuePress-theme-reco</a></span> <span data-v-64685f0e><i class="iconfont reco-copyright" data-v-64685f0e></i> <a data-v-64685f0e><span data-v-64685f0e>伊水河</span>
            
          <span data-v-64685f0e>2020 - </span>
          2021
        </a></span></div></div> <div data-v-2d5f533b><main class="page"><div class="page-title" style="display:none;"><h1 class="title">mobx常用方法梳理</h1> <div data-v-3b7f5bdf><i class="iconfont reco-account" data-v-3b7f5bdf><span data-v-3b7f5bdf>伊水河</span></i> <i class="iconfont reco-date" data-v-3b7f5bdf><span data-v-3b7f5bdf>2020-11-26</span></i> <i class="iconfont reco-eye" data-v-3b7f5bdf><span id="/guide/relearnMobx.html" data-flag-title="Your Article Title" class="leancloud-visitors" data-v-3b7f5bdf><a class="leancloud-visitors-count" style="font-size:.9rem;font-weight:normal;color:#999;"></a></span></i> <i class="iconfont reco-tag tags" data-v-3b7f5bdf><span class="tag-item" data-v-3b7f5bdf>mobx</span><span class="tag-item" data-v-3b7f5bdf>react</span></i></div></div> <div class="theme-reco-content content__default" style="display:none;"><p>使用react刚好一年，一直是用的mobx进行状态管理。前一段时间在使用mobx过程中突然发现最近所使用的方式都是有一定问题的，故重新梳理其使用方式。</p> <blockquote><p>本文适用mobx 4或5</p></blockquote> <p>mobx主要是创建响应式数据，然后当数据变化时通过一些方式来做出相应的处理，常用的方法有：</p> <ul><li>observable</li> <li>toJS</li> <li>computed</li> <li>action</li></ul> <p>下面我们来一一介绍</p> <blockquote><p>以上方法支持直接调用或装饰器方式，本文以装饰器来介绍。</p> <p>如若不支持装饰器，则需安装<code>@babel/plugin-proposal-decorators</code>，并在<code>.babelrc</code>中配置</p> <div class="language-json extra-class"><pre class="language-json"><code>  <span class="token punctuation">{</span>
      <span class="token property">&quot;plugins&quot;</span><span class="token operator">:</span> <span class="token punctuation">[</span> 
          <span class="token punctuation">[</span> 
              <span class="token string">&quot;@babel/plugin-proposal-decorators&quot;</span><span class="token punctuation">,</span>
              <span class="token punctuation">{</span><span class="token property">&quot;legacy&quot;</span><span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">}</span> 
          <span class="token punctuation">]</span> 
      <span class="token punctuation">]</span> 
  <span class="token punctuation">}</span>
</code></pre></div></blockquote> <h2 id="observable"><a href="#observable" class="header-anchor">#</a> observable</h2> <p>将一个对象变为可观察对象，用法比较简单：</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">import</span> <span class="token punctuation">{</span> observable <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'mobx'</span>

<span class="token keyword">class</span> <span class="token class-name">Store</span><span class="token punctuation">{</span>

    @observable
    obj<span class="token operator">=</span><span class="token punctuation">{</span>a<span class="token operator">:</span><span class="token number">1</span><span class="token punctuation">}</span>

    @observable
    num<span class="token operator">=</span><span class="token number">1</span>

<span class="token punctuation">}</span>
</code></pre></div><p>经过observable装饰过的属性即可成为响应式数据，供之后使用。</p> <blockquote><p>mobx@4使用的是<code>Object.defineProperty</code>，学过vue@2的应该明白上面代码中obj.a是可以监测的。如若要监测一个未定义的属性<code>obj.b</code>，这么写是无法监测的。可以使用官方提供的<code>extendObservable</code>来追加监测属性。</p></blockquote> <h2 id="tojs"><a href="#tojs" class="header-anchor">#</a> toJS</h2> <p>将通过observable转换过的数据转回普通的js对象。以上面代码为前提，假设它导出了<code>export default new Store()</code>，那么在使用的地方通常可以这么写：</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">import</span> <span class="token punctuation">{</span> toJS <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'mobx'</span>
<span class="token keyword">import</span> store <span class="token keyword">from</span> <span class="token string">'./store'</span>

<span class="token keyword">const</span> jsObj<span class="token operator">=</span><span class="token function">toJS</span><span class="token punctuation">(</span>store<span class="token punctuation">)</span>

</code></pre></div><p><code>jsObj</code>已是普通的js对象，可在其他地方使用。</p> <h2 id="computed"><a href="#computed" class="header-anchor">#</a> computed</h2> <p>根据现有可观察值生成一个新的值（类比vue的计算属性或vuex的getter）。用法：</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">import</span> <span class="token punctuation">{</span> observable<span class="token punctuation">,</span> computed <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'mobx'</span>

<span class="token keyword">class</span> <span class="token class-name">Store</span><span class="token punctuation">{</span>
    @observable n<span class="token operator">=</span><span class="token number">1</span>

    @computed <span class="token keyword">get</span> <span class="token function">nPlus1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span>n<span class="token operator">+</span><span class="token number">1</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>以上代码中的<code>nPlus1</code>在<code>n</code>变化时会重新计算，保持始终比<code>n</code>大1。那么怎么来改变<code>n</code>呢？那就要有请<code>action</code>了。</p> <h2 id="action"><a href="#action" class="header-anchor">#</a> action</h2> <p>用来修改可观察数据，仅限同步。（是否想到了vuex的mutation）</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">import</span> <span class="token punctuation">{</span> observable<span class="token punctuation">,</span> action <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'mobx'</span>

<span class="token keyword">class</span> <span class="token class-name">Store</span><span class="token punctuation">{</span>
    @observable order<span class="token operator">=</span><span class="token number">1</span>

    @action <span class="token function">setOrder</span><span class="token punctuation">(</span><span class="token parameter">val</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>order<span class="token operator">=</span>val
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>不建议直接更改<code>order</code>的值，在需要的地方通过调用<code>setOrder</code>来修改。</p> <blockquote><p>可以通过开启严格模式来禁止直接修改。<code>mobx.configure({enforceActions:true})</code></p></blockquote> <h2 id="异步修改状态"><a href="#异步修改状态" class="header-anchor">#</a> 异步修改状态</h2> <p>那么异步呢？实际开发中需要通过接口获取值来修改页面状态可是家常便饭。可通过以下几种方式来进行异步状态修改：</p> <h3 id="在需要修改状态的地方调用已有action"><a href="#在需要修改状态的地方调用已有action" class="header-anchor">#</a> 在需要修改状态的地方调用已有<code>action</code></h3> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">import</span> <span class="token punctuation">{</span> observable<span class="token punctuation">,</span> action <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'mobx'</span>

<span class="token keyword">class</span> <span class="token class-name">Store</span><span class="token punctuation">{</span>
    @observable order<span class="token operator">=</span><span class="token number">1</span>
    @observable order2<span class="token operator">=</span><span class="token number">1</span>

    @action <span class="token function">setOrder</span><span class="token punctuation">(</span><span class="token parameter">val</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>order<span class="token operator">=</span>val
    <span class="token punctuation">}</span>

    @action <span class="token function">setOrder2</span><span class="token punctuation">(</span><span class="token parameter">val</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>order2<span class="token operator">=</span>val
    <span class="token punctuation">}</span>

    <span class="token keyword">async</span> <span class="token function">af</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">const</span> <span class="token punctuation">{</span>no<span class="token punctuation">,</span>no2<span class="token punctuation">}</span><span class="token operator">=</span><span class="token keyword">await</span> <span class="token function">asyncFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">setOrder</span><span class="token punctuation">(</span>no<span class="token punctuation">)</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">setOrder2</span><span class="token punctuation">(</span>no2<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>上栗使用<code>async function</code>，<code>promise</code>在需要修改状态的地方调用已有<code>action</code>即可。</p> <blockquote><p>上面在<code>await</code>之前没有修改状态的话，是无需使用<code>action</code>包装的。之前一直有写，算是理解不到位了。</p></blockquote> <p>至此，已经可以很好的使用mobx了。使用react的话，配合mobx-react便可解决大部分问题。如果想要了解更多的话，继续往下看吧。</p> <h3 id="runinaction"><a href="#runinaction" class="header-anchor">#</a> runInAction</h3> <p><code>runInAction</code>可以避免我们去定义很多的action来修改数据。数据的修改可以放心的用之包裹起来，修改上栗：</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">import</span> <span class="token punctuation">{</span> observable<span class="token punctuation">,</span> runInAction <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'mobx'</span>

<span class="token keyword">class</span> <span class="token class-name">Store</span><span class="token punctuation">{</span>
    @observable order<span class="token operator">=</span><span class="token number">1</span>
    @observable order2<span class="token operator">=</span><span class="token number">1</span>

    <span class="token keyword">async</span> <span class="token function">af</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">const</span> <span class="token punctuation">{</span>no<span class="token punctuation">,</span>no2<span class="token punctuation">}</span><span class="token operator">=</span><span class="token keyword">await</span> <span class="token function">asyncFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token function">runInAction</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">=&gt;</span><span class="token punctuation">{</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>order<span class="token operator">=</span>no
            <span class="token keyword">this</span><span class="token punctuation">.</span>order2<span class="token operator">=</span>no2
        <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>可以看到代码简洁了许多。</p> <h3 id="flow"><a href="#flow" class="header-anchor">#</a> flow</h3> <p>flow接收一个generator，代码也非常简洁，同时也更好阅读，官方推荐。来看下写法，修改上面代码：</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">import</span> <span class="token punctuation">{</span> observable<span class="token punctuation">,</span> flow <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'mobx'</span>

<span class="token keyword">class</span> <span class="token class-name">Store</span><span class="token punctuation">{</span>
    @observable order<span class="token operator">=</span><span class="token number">1</span>
    @observable order2<span class="token operator">=</span><span class="token number">1</span>

    doSth<span class="token operator">=</span><span class="token function">flow</span><span class="token punctuation">(</span><span class="token keyword">function</span> <span class="token operator">*</span> <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">const</span> <span class="token punctuation">{</span>no<span class="token punctuation">,</span>no2<span class="token punctuation">}</span><span class="token operator">=</span>yeild <span class="token function">asyncFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>order<span class="token operator">=</span>no
        <span class="token keyword">this</span><span class="token punctuation">.</span>order2<span class="token operator">=</span>no2
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div><p>在需要的地方调用doSth即可</p> <h2 id="响应数据变化"><a href="#响应数据变化" class="header-anchor">#</a> 响应数据变化</h2> <p>到此为止已经可以定义和修改数据了，但是否少了些什么。数据变化后我们总要处理点什么吧，比如更新视图（没错，watch没跑了）。那就有请下面几位小伙伴啦。</p> <h3 id="autorun"><a href="#autorun" class="header-anchor">#</a> autorun</h3> <p>监测传入函数参数中用到的可观察数据：</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">import</span> <span class="token punctuation">{</span> observable<span class="token punctuation">,</span> action<span class="token punctuation">,</span> autorun <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'mobx'</span>

<span class="token keyword">class</span> <span class="token class-name">Store</span><span class="token punctuation">{</span>
    @observable order<span class="token operator">=</span><span class="token number">1</span>
<span class="token punctuation">}</span>

<span class="token keyword">const</span> store<span class="token operator">=</span><span class="token keyword">new</span> <span class="token class-name">Store</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token function">autorun</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>store<span class="token punctuation">.</span>order<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>上面代码当order变化时，便会触发传入autorun的函数，打印出新的order。因为autorun的函数入参中用到了order（store.order）</p> <blockquote><p>想要深入了解mobx会对哪些数据做出响应，可以参考：<a href="https://cn.mobx.js.org/best/react.html" target="_blank" rel="noopener noreferrer">MobX 会对什么作出反应?<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></p></blockquote> <h3 id="when"><a href="#when" class="header-anchor">#</a> when</h3> <p>有条件的监测，接收两个参数均为函数，第一个函数返回true时便会执行第二个函数</p> <p><code>when(()=&gt;someCondition,()=&gt;{ /**doSth*/ })</code></p> <h3 id="reaction"><a href="#reaction" class="header-anchor">#</a> reaction</h3> <p>可以自定义需要监测哪些字段，同样接受两个参数，第一个参数返回需要监测的字段，当其变化时便会执行第二个函数</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">import</span> <span class="token punctuation">{</span> observable<span class="token punctuation">,</span> reaction <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'mobx'</span>

<span class="token keyword">class</span> <span class="token class-name">Store</span><span class="token punctuation">{</span>
    @observable order<span class="token operator">=</span><span class="token number">1</span>
    @observable order2<span class="token operator">=</span><span class="token number">2</span>
<span class="token punctuation">}</span>

<span class="token keyword">const</span> store<span class="token operator">=</span><span class="token keyword">new</span> <span class="token class-name">Store</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token function">reaction</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">=&gt;</span>store<span class="token punctuation">.</span>order<span class="token punctuation">,</span><span class="token parameter">order</span> <span class="token operator">=&gt;</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>order<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>上栗中只有order变化时才会打印，而order2则不被监测。在某些地方使用也很方便，比如将分页数据的页码作为第一个参数的返回值，从而在第二个函数中做翻页请求（别瞅hook）。</p> <blockquote><p>历史原因导致项目无法升级支持hook的mobx-react。为了拥抱hook，前段时间写了个小扩展，就是用的reaction。
可以在mobx数据变化时更新hook组件。有兴趣的可以看下：</p> <p><a href="https://github.com/lixiang89/mobx-react-hook" target="_blank" rel="noopener noreferrer">mobx-react-hook<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>。</p></blockquote> <p>另外，这几个响应函数</p> <ul><li>会返回一个取消监测的函数<code>const disposer = autorun(()=&gt;{})</code>，调用<code>disposer()</code>之后便可取消监测。可在组件销毁时使用。</li> <li>比本文多一个入参，可配置响应函数的行为，位置在最后。</li></ul> <blockquote><p>更多内容参见<a href="https://cn.mobx.js.org/refguide/api.html" target="_blank" rel="noopener noreferrer">mobx文档<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></p></blockquote></div> <footer class="page-edit" style="display:none;"><!----> <!----></footer> <!----> <!----> <!----></main> <!----></div></div></div></div><div class="global-ui"><div class="back-to-ceiling" style="right:1rem;bottom:6rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;display:none;" data-v-c6073ba8 data-v-c6073ba8><svg t="1574745035067" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5404" class="icon" data-v-c6073ba8><path d="M526.60727968 10.90185116a27.675 27.675 0 0 0-29.21455937 0c-131.36607665 82.28402758-218.69155461 228.01873535-218.69155402 394.07834331a462.20625001 462.20625001 0 0 0 5.36959153 69.94390903c1.00431239 6.55289093-0.34802892 13.13561351-3.76865779 18.80351572-32.63518765 54.11355614-51.75690182 118.55860487-51.7569018 187.94566865a371.06718723 371.06718723 0 0 0 11.50484808 91.98906777c6.53300375 25.50556257 41.68394495 28.14064038 52.69160883 4.22606766 17.37162448-37.73630017 42.14135425-72.50938081 72.80769204-103.21549295 2.18761121 3.04276886 4.15646224 6.24463696 6.40373557 9.22774369a1871.4375 1871.4375 0 0 0 140.04691725 5.34970492 1866.36093723 1866.36093723 0 0 0 140.04691723-5.34970492c2.24727335-2.98310674 4.21612437-6.18497483 6.3937923-9.2178004 30.66633723 30.70611158 55.4360664 65.4791928 72.80769147 103.21549355 11.00766384 23.91457269 46.15860503 21.27949489 52.69160879-4.22606768a371.15156223 371.15156223 0 0 0 11.514792-91.99901164c0-69.36717486-19.13165746-133.82216804-51.75690182-187.92578088-3.42062944-5.66790279-4.76302748-12.26056868-3.76865837-18.80351632a462.20625001 462.20625001 0 0 0 5.36959269-69.943909c-0.00994388-166.08943902-87.32547796-311.81420293-218.6915546-394.09823051zM605.93803103 357.87693858a93.93749974 93.93749974 0 1 1-187.89594924 6.1e-7 93.93749974 93.93749974 0 0 1 187.89594924-6.1e-7z" p-id="5405" data-v-c6073ba8></path><path d="M429.50777625 765.63860547C429.50777625 803.39355007 466.44236686 1000.39046097 512.00932183 1000.39046097c45.56695499 0 82.4922232-197.00623328 82.5015456-234.7518555 0-37.75494459-36.9345906-68.35043303-82.4922232-68.34111062-45.57627738-0.00932239-82.52019037 30.59548842-82.51086798 68.34111062z" p-id="5406" data-v-c6073ba8></path></svg></div><APlayer audio="" fixed="true" theme="#b7daff" loop="loop" order="random" preload="auto" volume="0.7" mutex="true" lrc-type="3" list-folded="true" list-max-height="250" storage-name="vuepress-plugin-meting" id="aplayer-fixed"></APlayer></div></div>
    <script src="/assets/js/app.2d22f3f9.js" defer></script><script src="/assets/js/3.6721f6a0.js" defer></script><script src="/assets/js/1.546ea5a7.js" defer></script><script src="/assets/js/19.73f82cea.js" defer></script>
  </body>
</html>
